// -------------------------------------------------
// BlinKit - BlinKit Library
// -------------------------------------------------
//   File Name: kurl.cpp
// Description: Placeholder for KURL
//      Author: Ziming Li
//     Created: 2021-08-11
// -------------------------------------------------
// Copyright (C) 2021 MingYang Software Technology.
// -------------------------------------------------

#include "./kurl.h"

#include "blinkit/blink/renderer/wtf/text/TextEncoding.h"

namespace blink {

KURL::KURL(const KURL &base, const String &relative) : zed::url(base.combine(relative.stdUtf8()))
{
}

KURL::KURL(const KURL &base, const String &relative, const WTF::TextEncoding &encoding)
    : zed::url(base.combine(relative.stdUtf8()))
{
    ASSERT(zed::strequ(encoding.name(), "UTF-8")); // BKTODO: Support other encodings?
}

std::string KURL::ExtractFileName(void) const
{
    std::string path = get_path();
    size_t p = path.rfind('/');
    return std::string::npos != p ? path.substr(p + 1) : path;
}

String KURL::PartToString(const zed::url_parts::part& part) const
{
    ASSERT(is_valid());
    std::string_view scheme = piece_of(part);
    return String::fromUTF8(scheme.data(), scheme.length());
}

String KURL::strippedForUseAsHref(void) const
{
    ZASSERT(raw_parts().username.length == 0 && raw_parts().password.length == 0); // BKTODO:
    return String::fromStdUTF8(spec());
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

const KURL& blankURL(void)
{
    static KURL staticBlankURL("about:blank");
    return staticBlankURL;
}

bool equalIgnoringFragmentIdentifier(const KURL &a, const KURL &b)
{
    size_t la = a.spec().length();
    if (a.raw_parts().ref.length > 0)
        la -= a.raw_parts().ref.length;

    size_t lb = b.spec().length();
    if (b.raw_parts().ref.length > 0)
        lb -= b.raw_parts().ref.length;

    if (la != lb)
        return false;

    const char *psa = a.spec().data();
    const char *psb = b.spec().data();
    for (size_t i = 0; i < la; ++i)
    {
        if (*psa != *psb)
            return false;

        ++psa; ++psb;
    }
    return true;
}

bool protocolIs(const String &url, const char *protocol)
{
    const size_t len = strlen(protocol);

    if (url.length() <= len)
        return false;

    if (url.is8Bit())
    {
        const LChar *ps = url.characters8();
        if (0 != memcmp(ps, protocol, len))
            return false;
        return ps[len] == ':';
    }

    const UChar *ps = url.characters16();
    for (size_t i = 0; i < len; ++i)
    {
        if (ps[i] != protocol[i])
            return false;
    }
    return ps[len] == ':';
}

bool protocolIsJavaScript(const String &url)
{
    return protocolIs(url, "javascript");
}

} // namespace blink
